package com.salt;

import com.salt.common.RestResponse;
import com.salt.security.BaseUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @author HaiBo Kuang
 * @date 2021年04月16日 上午 10:35
 */
@RestController
@RequestMapping("demo")
public class DemoController {
    private final Logger logger = LoggerFactory.getLogger("Demo_Controller");

    @GetMapping("userInfo")
    public ResponseEntity<?> userInfo(@AuthenticationPrincipal BaseUserDetails userDetails) {
        logger.info("<==用户信息==>");
        logger.info(userDetails.getUsername());
        logger.info("<==用户信息==>");
        return RestResponse.success();
    }

    @GetMapping("userInfoObject")
    public ResponseEntity<?> userInfoObject() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        logger.info("principal:{}", principal.toString());
        if ((!(principal instanceof String))) {
            BaseUserDetails userDetails = (BaseUserDetails) principal;
            logger.info("<==用户信息==>");
            logger.info(userDetails.getUsername());
            logger.info("<==用户信息==>");
        }
        return RestResponse.success();
    }

    @PostMapping("file")
    public String testFile(@RequestParam("file") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        File storeFile = new File("/data/" + fileName);
        file.transferTo(storeFile);
        return "SUCCESS";
    }

    @GetMapping("testAsync")
    public String testAsync() {
        logger.info("<===我在前:time:{}===>", new Date());
        testAsyncVoid();
        logger.info("<====我在后:time:{}===>", new Date());
        return "testAsync";
    }

    @Async
    public void testAsyncVoid() {
        logger.info("<===异步方法执行:time:{}====>", new Date());
    }
}
